import React, { useEffect, useRef, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

// 定义地图组件的属性
interface MapComponentProps {
  center?: [number, number]; // 地图中心点坐标 [经度, 纬度]
  zoom?: number; // 缩放级别
  markers?: Array<{
    position: [number, number];
    title?: string;
    label?: string;
    icon?: string;
    extData?: any;
  }>; // 标记点
  polylines?: Array<{
    path: Array<[number, number]>;
    strokeColor?: string;
    strokeWeight?: number;
    strokeOpacity?: number;
    extData?: any;
  }>; // 折线
  onMarkerClick?: (marker: any) => void; // 标记点点击事件
  onMapClick?: (e: any) => void; // 地图点击事件
  style?: React.CSSProperties; // 地图容器样式
}

// 定义全局类型，以便在组件中使用高德地图API
declare global {
  interface Window {
    AMap: any;
    _amap_init_callback?: () => void;
  }
}

// 高德地图API密钥
const AMAP_KEY = '5167e1072a5f26767abb39b6f579c07c'; // 使用Web端Key

// 设置Canvas的willReadFrequently属性
const setCanvasWillReadFrequently = (container: HTMLElement | null) => {
  if (!container) return;
  
  // 找到所有当前存在的Canvas元素并设置属性
  const canvasElements = container.querySelectorAll('canvas');
  canvasElements.forEach(canvas => {
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    if (ctx && ctx instanceof CanvasRenderingContext2D) {
      // 空操作，只是确保使用了带有willReadFrequently的上下文
    }
    canvas.setAttribute('willReadFrequently', 'true');
  });
};

// 拦截Canvas创建
const patchCanvas = () => {
  // 保存原始方法
  const originalGetContext = HTMLCanvasElement.prototype.getContext;

  // 注释掉类型覆盖，改用运行时方法替换
  // @ts-ignore - 我们需要忽略类型检查，因为我们正在修改底层API
  HTMLCanvasElement.prototype.getContext = function() {
    // 如果是2d上下文，添加willReadFrequently属性
    if (arguments[0] === '2d') {
      let attrs = arguments[1] || {};
      attrs = { ...attrs, willReadFrequently: true };
      return originalGetContext.call(this, '2d', attrs);
    }
    
    // 其他类型的上下文直接传递给原始方法，避免使用apply
    if (arguments.length === 1) {
      return originalGetContext.call(this, arguments[0]);
    } else if (arguments.length === 2) {
      return originalGetContext.call(this, arguments[0], arguments[1]);
    } else {
      // 回退情况，通常不会执行到这里
      return originalGetContext.call(this, arguments[0]);
    }
  };
};

const MapComponent: React.FC<MapComponentProps> = ({
  center = [121.473667, 31.230525], // 默认上海中心
  zoom = 11,
  markers = [],
  polylines = [],
  onMarkerClick,
  onMapClick,
  style = { height: '500px', width: '100%' }
}) => {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const [mapInstance, setMapInstance] = useState<any>(null);
  const [mapMarkers, setMapMarkers] = useState<any[]>([]);
  const [mapPolylines, setMapPolylines] = useState<any[]>([]);
  const [mapLoaded, setMapLoaded] = useState<boolean>(false);

  // 在首次渲染时修改Canvas.getContext
  useEffect(() => {
    // 修改Canvas.prototype.getContext来默认添加willReadFrequently
    patchCanvas();
  }, []);

  // 初始化地图
  useEffect(() => {
    // 如果地图实例已存在，则不重复创建
    if (mapInstance || !mapContainerRef.current) return;

    let isMounted = true;
    
    const loadMap = async () => {
      try {
        // 在加载高德地图之前先设置MutationObserver来监控DOM变化
        const observer = new MutationObserver((mutations) => {
          mutations.forEach((mutation) => {
            if (mutation.addedNodes.length > 0) {
              // 当有新节点添加时，检查并设置Canvas属性
              if (mapContainerRef.current) {
                setCanvasWillReadFrequently(mapContainerRef.current);
              }
            }
          });
        });
        
        // 开始监视DOM变化
        if (mapContainerRef.current) {
          observer.observe(mapContainerRef.current, { 
            childList: true, 
            subtree: true 
          });
        }

        const AMap = await AMapLoader.load({
          key: AMAP_KEY,
          version: '2.0',
          plugins: [
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.HawkEye',
            'AMap.MapType',
            'AMap.GeometryUtil',
            'AMap.Driving',
            'AMap.Transfer'
          ]
        });
        
        if (!isMounted || !mapContainerRef.current) return;
        
        // 创建地图实例
        const map = new AMap.Map(mapContainerRef.current, {
          viewMode: '2D',
          zoom,
          center,
          // 添加渲染配置以减少性能问题
          renderOptions: {
            preserveDrawingBuffer: true
          }
        });

        // 添加工具条和比例尺
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());

        // 添加地图点击事件
        if (onMapClick) {
          map.on('click', onMapClick);
        }
        
        // 立即设置Canvas元素的willReadFrequently属性
        setCanvasWillReadFrequently(mapContainerRef.current);
        
        // 也在短时间后再设置一次，确保处理了所有动态创建的Canvas
        setTimeout(() => {
          if (mapContainerRef.current) {
            setCanvasWillReadFrequently(mapContainerRef.current);
          }
        }, 100);

        // 设置完成事件，确保在地图完全加载后也设置Canvas属性
        map.on('complete', function() {
          if (mapContainerRef.current) {
            setCanvasWillReadFrequently(mapContainerRef.current);
          }
          
          // 设置地图限制以优化性能
          if (map.setLimit) {
            map.setLimit({
              fps: 30 // 限制帧率
            });
          }
        });
        
        // 减少不必要的重绘，优化渲染性能
        if (map.setMapStyle) {
          // 设置地图渲染方式为帧渲染，减少渲染频率
          map.setMapStyle('amap://styles/normal');
        }
        
        // 限制地图的交互方式，减少重绘次数
        if (map.setStatus) {
          map.setStatus({
            animateEnable: true,
            dragEnable: true,
            zoomEnable: true,
            rotateEnable: false,  // 禁用旋转以减少不必要的渲染
            jogEnable: false      // 禁用缓动效果
          });
        }

        setMapInstance(map);
        setMapLoaded(true);
      } catch (e) {
        console.error('地图加载失败:', e);
      }
    };
    
    loadMap();

    // 组件卸载时清理地图实例
    return () => {
      isMounted = false;
      if (mapInstance) {
        try {
          mapInstance.destroy();
        } catch (e) {
          console.error('销毁地图实例失败:', e);
        }
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mapContainerRef.current]); // 仅在组件挂载时执行

  // 当中心点或缩放级别变化时更新地图
  useEffect(() => {
    if (!mapInstance || !mapLoaded) return;

    try {
      mapInstance.setZoomAndCenter(zoom, center);
    } catch (e) {
      console.error('更新地图视图失败:', e);
    }
  }, [mapInstance, center, zoom, mapLoaded]);

  // 添加或更新标记点
  useEffect(() => {
    if (!mapInstance || !mapLoaded || !window.AMap) return;

    try {
      // 清除旧的标记点
      mapMarkers.forEach(marker => {
        mapInstance.remove(marker);
      });

      // 创建新的标记点
      const newMarkers = markers.map((markerData, index) => {
        const marker = new window.AMap.Marker({
          position: markerData.position,
          title: markerData.title || `标记 ${index + 1}`,
          label: markerData.label ? {
            content: markerData.label,
            direction: 'right'
          } : undefined,
          icon: markerData.icon,
          extData: markerData.extData
        });

        // 添加点击事件
        if (onMarkerClick) {
          marker.on('click', () => onMarkerClick(marker));
        }

        mapInstance.add(marker);
        return marker;
      });

      setMapMarkers(newMarkers);
      
      // 每次添加新标记后检查并设置Canvas属性
      setTimeout(() => {
        if (mapContainerRef.current) {
          setCanvasWillReadFrequently(mapContainerRef.current);
        }
      }, 0);
    } catch (e) {
      console.error('添加标记点失败:', e);
    }
    
    // 清理函数
    return () => {
      try {
        mapMarkers.forEach(marker => {
          if (mapInstance && marker) {
            mapInstance.remove(marker);
          }
        });
      } catch (e) {
        console.error('清除标记点失败:', e);
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mapInstance, markers, onMarkerClick, mapLoaded]);

  // 添加或更新折线
  useEffect(() => {
    if (!mapInstance || !mapLoaded || !window.AMap) return;

    try {
      // 清除旧的折线
      mapPolylines.forEach(polyline => {
        mapInstance.remove(polyline);
      });

      // 创建新的折线
      const newPolylines = polylines.map((polylineData, index) => {
        const polyline = new window.AMap.Polyline({
          path: polylineData.path,
          strokeColor: polylineData.strokeColor || '#3366FF',
          strokeWeight: polylineData.strokeWeight || 6,
          strokeOpacity: polylineData.strokeOpacity || 0.8,
          extData: polylineData.extData
        });

        mapInstance.add(polyline);
        return polyline;
      });

      setMapPolylines(newPolylines);
      
      // 每次添加新折线后检查并设置Canvas属性
      setTimeout(() => {
        if (mapContainerRef.current) {
          setCanvasWillReadFrequently(mapContainerRef.current);
        }
      }, 0);
    } catch (e) {
      console.error('添加折线失败:', e);
    }
    
    // 清理函数
    return () => {
      try {
        mapPolylines.forEach(polyline => {
          if (mapInstance && polyline) {
            mapInstance.remove(polyline);
          }
        });
      } catch (e) {
        console.error('清除折线失败:', e);
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mapInstance, polylines, mapLoaded]);

  return (
    <div ref={mapContainerRef} style={style}>
      {!mapLoaded && (
        <div style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: '#f0f0f0',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          地图加载中...
        </div>
      )}
    </div>
  );
};

export default MapComponent;